<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <div class="content">
          <NSpace>
            <NForm
              ref="formRef"
              :model="formValue"
              :rules="rules"
              label-placement="left"
              :label-width="115"
              label-align="right"
              require-mark-placement="left"
            >
              <NSpace>
                <NFormItem
                  label="证书编号:"
                  path="certificateNo"
                >
                  <NInput
                    v-model:value="formValue.certificateNo"
                    placeholder="输入证书编号"
                    style="width: 250px"
                    @blur="checkCertificateNo"
                  />
                </NFormItem>
                <NFormItem
                  label="藏家:"
                  path="collectorId"
                >
                  <NSelect
                    :options="listNameOption"
                    :value="formValue.collectorId"
                    @update:value="handleUpdateCollectorId"
                    placeholder="藏家"
                    style="width: 250px"
                    filterable
                  />
                  <!-- <NInput
                    v-model:value="formValue.collectorId"
                    placeholder="输入藏家"
                    style="width: 250px"
                  /> -->
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="经手人:"
                  path="handledBy"
                >
                  <NInput
                    v-model:value="formValue.handledBy"
                    placeholder="输入经手人"
                    style="width: 250px"
                  />
                </NFormItem>
                <NFormItem
                  label="捐赠数量:"
                  path="donateNum"
                >
                  <NInputNumber
                    @keydown="(e) => e.key === '.' && e.preventDefault()"
                    v-model:value="formValue.donateNum"
                    placeholder="输入捐赠数量"
                    style="width: 250px"
                    :show-button="false"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="捐赠内容:"
                  path="donateContent"
                >
                  <NInput
                    v-model:value="formValue.donateContent"
                    placeholder="输入捐赠内容"
                    style="width: 250px"
                  />
                </NFormItem>
                <NFormItem
                  label="所属批次:"
                  path="batchIds"
                >
                  <NSelect
                    :options="listOption"
                    v-model:value="formValue.batchIds"
                    multiple
                    placeholder="请选择所属批次"
                    clearable
                    style="width: 250px"
                    filterable
                    @update:value="valueChange"
                    :render-option="renderOption"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  path="certificateTypeCode"
                  label="证书类型:"
                >
                  <NSelect
                    :options="listOptionCer"
                    v-model:value="formValue.certificateTypeCode"
                    placeholder="请选择证书类型"
                    @update:value="valueChange1"
                    clearable
                    style="width: 250px"
                  />
                </NFormItem>
                <NFormItem
                  label="规格内容:"
                  v-if="formValue.certificateTypeCode == 'A6103'"
                  path="certificateSpecs"
                >
                  <NInput
                    v-model:value="formValue.certificateSpecs"
                    placeholder="输入规格内容"
                    style="width: 250px"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="备注:"
                  path="notes"
                >
                  <NInput
                    v-model:value="formValue.notes"
                    placeholder="输入备注"
                    style="width: 630px"
                    type="textarea"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="附件:"
                  path="fileIds"
                >
                  <FUploader
                    :file-list="fileList"
                    @update:fileList="handleUploadList"
                    style="width: 250px"
                  />
                </NFormItem>
              </NSpace>
            </NForm>
          </NSpace>
        </div>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        取消
      </NButton>
      <NButton
        type="primary"
        style="width: 78px"
        @click="confirm"
        :disabled="loading"
        :loading="loading"
      >
        保存
      </NButton>
    </NSpace>
  </FixedAction>
</template>

<script setup lang="ts">
import { ref, onMounted, type VNode, reactive, h } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NInputNumber,
  NFormItem,
  NButton,
  NScrollbar,
  NSelect,
  useMessage,
  NTooltip,
  type SelectOption
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
// import VUpload from '@/views/OA/Common/Upload.vue'
import type { HttpResponse } from '@/utils/http'
import FUploader from '@/views/Collection/Collect/Batch/components/FUploader.vue'

const renderOption = ({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })
const tags = useTagStore().tags
const message = useMessage()
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const listOption = ref([])
const listOptionCer = ref([])
const formValue = reactive({
  certificateNo: '',
  collectorId: '',
  handledBy: '',
  donateNum: null,
  donateContent: '',
  certificateTypeCode: '',
  certificateSpecs: '',
  batchIds: [],
  fileIds: '',
  notes: ''
})

const fileList: any = ref([])
const rules = {
  certificateNo: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('请输入证书编号')
      if (value.length > 15) return new Error('证书编号字数不得超过15')
      return true
    }
  },
  collectorId: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('请输入藏家')
      if (value.length > 10) return new Error('藏家字数不得超过5')
      return true
    }
  },
  handledBy: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('请输入经手人')
      if (value.length > 10) return new Error('经手人字数不得超过5')
      return true
    }
  },
  donateNum: {
    required: true,
    trigger: ['input', 'blur'],
    type: 'number',
    validator: (_: any, value: any) => {
      if (value == null) return new Error('请输入捐赠数量')
      if (value < 1) return new Error('捐赠数量不得小于1')
      if (value > 99999999) return new Error('捐赠数量不得超过8位数')
      return true
    }
    // validator: (_: any, value: any) => {
    //   if (value.length == 0) return new Error('请输入捐赠数量')
    //   if (!/^[0,9]*/.test(value) || value < 1) return new Error('捐赠数量必须大于0的整数')
    //   if (value.length > 7) return new Error('捐赠数量字数不得超过10000000')
    //   return true
    // }
  },
  // donateContent: {
  //   required: true,
  //   trigger: ['input', 'blur', 'change'],
  //   validator: (_: any, value: any) => {
  //     if (value.length == 0) return new Error('请输入捐赠内容')
  //     if (value.length > 30) return new Error('捐赠内容字数不得超过100')
  //     return true
  //   }
  // },
  batchIds: {
    required: true,
    trigger: ['change', 'blur', 'input'],
    validator: (_: any, value: any) => {
      console.log(value)
      if (value.length == 0) return new Error('请选择所属批次')
      return true
    }
  },
  certificateTypeCode: {
    required: true,
    trigger: ['change', 'blur', 'input'],
    validator: (_: any, value: any) => {
      console.log(value)
      if (!value) return new Error('请选择证书类型')
      return true
    }
  },
  certificateSpecs: {
    required: true,
    trigger: ['change', 'blur', 'input'],
    validator: (_: any, value: any) => {
      if (!value && formValue.certificateTypeCode == 'A6103') return new Error('请输入其他规格')
      if (value.length == 0) return new Error('请输入规格内容')
      if (value.length > 100) return new Error('规格内容字数不得超过100')
      return true
    }
  },
  notes: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length > 200) return new Error('备注字数不得超过200')
      return true
    }
  }
}
// 附件
const handleUploadList = (v: any) => {
  formValue.fileIds = v.map((e: any) => e.file?.remoteId).join(',')
  fileList.value = v
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
const handleUpdateCollectorId = (value: string) => {
  formValue.collectorId = value as any
  formValue.batchIds = []
  getFunction(null, value)
}
let tempCertificateNo = ref() //上一步 证书编号
const getInitialCertificateNo = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseDonateCertificate',
    api: 'getCertificateNo'
  })
  if (error) return message.error(error.message)
  tempCertificateNo.value = res.data
  formValue.certificateNo = res.data
}
const checkCertificateNo = async (e: any) => {
  console.log(formValue.certificateNo, e, tempCertificateNo.value)
  if (!e.target.value) return //空值不校验
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseDonateCertificate',
    api: 'checkRepeat',
    override: {
      params: {
        certificateNo: e.target.value
      }
    }
  })
  if (error) {
    formValue.certificateNo = tempCertificateNo.value
    return message.error(error.message)
  } else if (!res.data.canUse) {
    formValue.certificateNo = tempCertificateNo.value
    return message.error(res.data.error)
  }
  tempCertificateNo.value = e.target.value
}
const listNameOption = ref<any>([])
//藏家姓名下拉
const getNameFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'controllerOptions'
  })
  if (error) return message.error(error.message)
  listNameOption.value = res.data
}
//所属批次下拉
const getFunction = async (v?: any, m?: any) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseDonateCertificate',
    api: 'listBatchOptionsByCollectorIdList',
    override: {
      params: {
        collectorId: m,
        batchName: v
        // id: route.params.id as never
      }
    }
  })
  if (error) return message.error(error.message)
  listOption.value = res.data
}
const getFunctionCer = async () => {
  listOptionCer.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseDonateCertificate',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A61'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOptionCer.value.push({ label: i.dicName, value: i.dicCode })
  })
}
const valueChange1 = (v: any) => {
  console.log(v)
  formValue.certificateSpecs = ''
}
const valueChange = (v: any) => {
  console.log(v)
  formValue.batchIds = v
}
const queryListOption = (v: any) => {
  // console.log(v)
  getFunction(v)
}
//修改
const confirm = () => {
  formRef.value?.validate(async (err: any) => {
    if (err) return
    if (formValue.batchIds.length > 0) {
      // @ts-ignore
      formValue.batchIds = formValue.batchIds.join(',')
    }
    loading.value = true
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'baseDonateCertificate',
      api: 'save',
      override: {
        data: {
          ...formValue
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    message.success(res.msg)
    goBack()
  })
}
onMounted(() => {
  getFunction()
  getNameFunction()
  getFunctionCer()
  getInitialCertificateNo()
})
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        width: 360rem;
        height: 130rem;
        background: #e1e1e1;
        margin-bottom: 25rem;
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
